package com.syni.mdd.yhd.common.all.service.impl;

import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsUserReceCouponDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.BaseReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsFullCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.enums.business.CouponEnums;
import com.syni.mdd.yhd.common.all.listen.userRece.UserReceEvent;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.market.BmsMarketReceService;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.TokenManager;
import com.syni.mdd.sjb.common.component.utils.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsUserReceCouponServiceImpl extends BaseService<BmsUserReceCoupon, Integer> implements BmsUserReceCouponService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsUserReceCouponDao bmsUserReceCouponDao;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsMarketReceService bmsMarketReceService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsUserBusinessAuthService bmsUserBusinessAuthService;

    @Override
    public BmsUserReceCouponDao getBaseDao() {
        return bmsUserReceCouponDao;
    }

    @Override
    public Map<String, Object> userGetCoupon(BaseReDto baseReDto) {
        //首先处理某个用户是否领了券
        BmsUser bmsUser = TokenManager.getUser(Integer.parseInt(baseReDto.getUserId()));
        Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap = new HashMap<>();
        //先查出之前该用户的中将记录
        if(bmsUser.getOpenid() != null) {
            bmsBusinessCouponMap = bmsMarketReceService.handleReceCoupon(bmsUser.getOpenid());
        }
        Integer pageSize = baseReDto.getPageSize();
        Integer pageNum = baseReDto.getPageNum();
        Integer userId = Integer.parseInt(baseReDto.getUserId());
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("expireTime_GTTE",new Date());
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("businessId_NN",Constants.COMMON_FLAG_TRUE_INT);
        List<BmsUserReceCoupon> bmsUserReceCoupons;
        if(pageNum != null && pageSize != null){
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
            bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        }else {
            Sort sort = Sort.by(Sort.Direction.DESC,"newTime");
            bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),sort);
        }
        setMarketReceHandle(bmsUserReceCoupons,bmsBusinessCouponMap);
        setBmsUserReceCoupon(bmsUserReceCoupons);
        return ResultMapHelper.success(bmsUserReceCoupons, ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetCoupon_V4(BaseReDto baseReDto) {
        //首先处理某个用户是否领了券
        BmsUser bmsUser = TokenManager.getUser(Integer.parseInt(baseReDto.getUserId()));
        Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap = new HashMap<>();
        //先查出之前该用户的中将记录
        if(bmsUser.getOpenid() != null) {
            bmsBusinessCouponMap = bmsMarketReceService.handleReceCoupon(bmsUser.getOpenid());
        }
        Integer pageSize = baseReDto.getPageSize();
        Integer pageNum = baseReDto.getPageNum();
        Integer userId = Integer.parseInt(baseReDto.getUserId());
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("expireTime_GTTE",new Date());
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        List<BmsUserReceCoupon> bmsUserReceCoupons;
        if(pageNum != null && pageSize != null){
            Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
            bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        }else {
            Sort sort = Sort.by(Sort.Direction.DESC,"newTime");
            bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),sort);
        }
        setMarketReceHandle(bmsUserReceCoupons,bmsBusinessCouponMap);
        setBmsUserReceCoupon(bmsUserReceCoupons);
        return ResultMapHelper.success(bmsUserReceCoupons, ResultMsg.MSG_GET_SUCCESS);
    }

    public void setBmsUserReceCoupon(List<BmsUserReceCoupon> bmsUserReceCoupons){
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                businessIds.add(bmsUserReceCoupon.getBusinessId());
                if(bmsUserReceCoupon.getBmsFullCoupon() != null){
                    BmsFullCoupon bmsFullCoupon = new BmsFullCoupon();
                    BeanUtils.copyProperties(bmsUserReceCoupon.getBmsFullCoupon(),bmsFullCoupon);
                    bmsFullCoupon.setEndTime(bmsUserReceCoupon.getExpireTime());
                    bmsUserReceCoupon.setBmsFullCoupon(bmsFullCoupon);
                }
                if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                    BmsBusinessCoupon bmsBusinessCoupon = new BmsBusinessCoupon();
                    BeanUtils.copyProperties(bmsUserReceCoupon.getBmsBusinessCoupon(),bmsBusinessCoupon);
                    bmsBusinessCoupon.setEndTime(bmsUserReceCoupon.getExpireTime());
                    bmsUserReceCoupon.setBmsBusinessCoupon(bmsBusinessCoupon);
                }
            }
            Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsBusinessMap.containsKey(bmsUserReceCoupon.getBusinessId())){
                    if(bmsUserReceCoupon.getBmsFullCoupon() != null){
                        bmsUserReceCoupon.getBmsFullCoupon().setBmsBusiness(bmsBusinessMap.get(bmsUserReceCoupon.getBusinessId()));
                    }else if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                        bmsBusinessCouponService.setBusinessCoupons(bmsUserReceCoupon.getBmsBusinessCoupon());
                        bmsUserReceCoupon.getBmsBusinessCoupon().setBmsBusiness(bmsBusinessMap.get(bmsUserReceCoupon.getBusinessId()));
                    }
                }
            }
        }
    }

    @Override
    public Map<String, Object> userGetOverExpireCoupon(ParamsMap paramsMap) {
        BmsUser bmsUser = TokenManager.getUser(paramsMap.getInteger("userIdentify"));
        Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap = new HashMap<>();
        //先查出之前该用户的中将记录
        if(bmsUser.getOpenid() != null) {
            bmsBusinessCouponMap = bmsMarketReceService.handleReceCoupon(bmsUser.getOpenid());
        }
        //已使用
        final int alreadyUse = 1;
        //已过期
        final int alreadyExpired = 2;
        Integer type = paramsMap.getInteger("type");
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("businessId_NN",Constants.COMMON_FLAG_TRUE_INT);
        if(type == alreadyUse){
            conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        }else if(type == alreadyExpired) {
            conditionMap.put("expireTime_LTTE",new Date());
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
        Page<BmsUserReceCoupon> receCouponPage = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsUserReceCoupon> bmsUserReceCoupons = receCouponPage.getContent();
        //处理领券逻辑
        setMarketReceHandle(bmsUserReceCoupons,bmsBusinessCouponMap);
        handleExpireUserRece(bmsUserReceCoupons);
        Map<String,Object> userData = new HashMap<>();
        userData.put("count",receCouponPage.getTotalElements());
        handleBmsUserRece(bmsUserReceCoupons);
        return ResultMapHelper.success(bmsUserReceCoupons,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> userGetOverExpireCoupon_V4(ParamsMap paramsMap) {
        BmsUser bmsUser = TokenManager.getUser(paramsMap.getInteger("userIdentify"));
        Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap = new HashMap<>();
        //先查出之前该用户的中将记录
        if(bmsUser.getOpenid() != null) {
            bmsBusinessCouponMap = bmsMarketReceService.handleReceCoupon(bmsUser.getOpenid());
        }
        //已使用
        final int alreadyUse = 1;
        //已过期
        final int alreadyExpired = 2;
        Integer type = paramsMap.getInteger("type");
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer pageNum = paramsMap.getInteger("pageNum");
        Integer pageSize = paramsMap.getInteger("pageSize");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        if(type == alreadyUse){
            conditionMap.put("status",Constants.COMMON_FLAG_TRUE_INT);
        }else if(type == alreadyExpired) {
            conditionMap.put("expireTime_LTTE",new Date());
        }
        Pageable pageable = BmsCommonService.getPageable(pageNum,pageSize, Sort.Direction.DESC,"newTime");
        Page<BmsUserReceCoupon> receCouponPage = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsUserReceCoupon> bmsUserReceCoupons = receCouponPage.getContent();
        //处理领券逻辑
        setMarketReceHandle(bmsUserReceCoupons,bmsBusinessCouponMap);
        handleExpireUserRece(bmsUserReceCoupons);
        Map<String,Object> userData = new HashMap<>();
        userData.put("count",receCouponPage.getTotalElements());
        handleBmsUserRece(bmsUserReceCoupons);
        return ResultMapHelper.success(bmsUserReceCoupons,userData,ResultMsg.MSG_GET_SUCCESS);
    }

    private void setMarketReceHandle(List<BmsUserReceCoupon> bmsUserReceCoupons, Map<Integer, BmsBusinessCoupon> bmsBusinessCouponMap){
        for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons) {
            if(bmsUserReceCoupon.getBmsBusinessCoupon() == null) {
                if (bmsBusinessCouponMap.containsKey(bmsUserReceCoupon.getBusinessCouponId())) {
                    bmsUserReceCoupon.setBmsBusinessCoupon(bmsBusinessCouponMap.get(bmsUserReceCoupon.getBusinessCouponId()));
                }
            }
        }
    }

    private void handleExpireUserRece(List<BmsUserReceCoupon> bmsUserReceCoupons) {
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getStatus() == Constants.IS_NO_USE) {
                    long expireTime = bmsUserReceCoupon.getExpireTime().getTime();
                    long nowTime = DateTimeUtils.getCurrentTime().getTime();
                    if (nowTime >= expireTime) {
                        bmsUserReceCoupon.setStatus(Constants.IS_OVER_EXPIRE);
                    }
                }
            }
            bmsUserReceCouponDao.saveAll(bmsUserReceCoupons);
        }
    }

    public void handleBmsUserRece(List<BmsUserReceCoupon> bmsUserReceCoupons){
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            Set<Integer> businessIds = bmsUserReceCoupons.stream().map(BmsUserReceCoupon::getBusinessId).collect(Collectors.toSet());
            Map<Integer, BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsBusinessMap.containsKey(bmsUserReceCoupon.getBusinessId())){
                    if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE) {
                        if (bmsUserReceCoupon.getBmsFullCoupon() != null) {
                            bmsUserReceCoupon.getBmsFullCoupon().setBmsBusiness(bmsBusinessMap.get(bmsUserReceCoupon.getBusinessId()));
                            bmsUserReceCoupon.getBmsFullCoupon().setEndTime(bmsUserReceCoupon.getExpireTime());
                        }
                    }
                    else if(bmsUserReceCoupon.getType() == Constants.BUSINESS_PRODUCE){
                        bmsUserReceCoupon.getBmsBusinessCoupon().setBmsBusiness(bmsBusinessMap.get(bmsUserReceCoupon.getBusinessId()));
                        bmsBusinessCouponService.setBusinessCoupons(bmsUserReceCoupon.getBmsBusinessCoupon());
                    }
                }
            }
        }
    }

    @Override
    public Map<String, Object> getMyFullCoupon(BaseReDto baseReDto) {
        Integer userId = Integer.parseInt(baseReDto.getUserId());
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("type",Constants.USER_RECE_FULL_COUPON);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_GTTE",new Date());
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap));
        if(!(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_NO_FULL_COUPON,ResultMsg.CODE_NO_FULL_COUPON);
        }
        return ResultMapHelper.success(bmsUserReceCoupons.get(0),ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getMyFullCouponv2(ParamsMap paramsMap) {
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("businessId",businessId);
        conditionMap.put("type",Constants.USER_RECE_FULL_COUPON);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_GTTE",new Date());
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap));
        if(!(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_NO_FULL_COUPON,ResultMsg.CODE_NO_FULL_COUPON);
        }
        return ResultMapHelper.success(bmsUserReceCoupons.get(0),ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public void updateFullCouponIsUse(Integer fullCouponId) {
        Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponDao.findById(fullCouponId);
        if(bmsUserReceCouponOptional.isPresent()){
            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
            bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_FALSE_INT);
            bmsUserReceCoupon.setUseTime(null);
            bmsUserReceCouponDao.save(bmsUserReceCoupon);
        }
    }

    @Override
    public Map<Integer, BmsUserReceCoupon> getUserFullCouponMap(Set<Integer> userReceFullIds) {
        Map<Integer,BmsUserReceCoupon> bmsUserReceCouponMap = new HashMap<>();
        if(userReceFullIds.size() > 0){
            List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findByIdIn(userReceFullIds);
            if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
                for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                    bmsUserReceCouponMap.put(bmsUserReceCoupon.getId(),bmsUserReceCoupon);
                }
            }
        }
        return bmsUserReceCouponMap;
    }

    @Override
    public void removeFullCouponUseNum(Integer fullCouponId) {
        Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponDao.findById(fullCouponId);
        if(bmsUserReceCouponOptional.isPresent()){
            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
            String redisKey = Constants.REDIS_KEY_FULL_COUPON_USE_NUM + bmsUserReceCoupon.getFullCouponId();
            if (redisTemplate.hasKey(redisKey)) {
                Integer useNum = Integer.parseInt(redisTemplate.opsForValue().get(redisKey).toString());
                long restTime = redisTemplate.getExpire(redisKey);
                useNum = useNum - 1;
                if(useNum <= 0){
                    redisTemplate.delete(redisKey);
                }else {
                    redisTemplate.opsForValue().set(redisKey, useNum,restTime, TimeUnit.SECONDS);
                }
            }
        }
    }

    @Override
    public Map<Integer, Map<String,Double>> countOrderTotalReceive(Set userReceIds) {
        Map<Integer,Map<String,Double>> resultMap = new HashMap<>();
        List<Map<String,Object>> userReceMapByPay = bmsDxOrderStatusService.countUserReceCoupon(userReceIds);
        //设置买单订单
        if(userReceMapByPay.size() > 0){
            for(Map<String,Object> userRecePay : userReceMapByPay){
                Integer businessId = Integer.parseInt(userRecePay.get("businessId").toString());
                //收入总金额
                Double total = Double.parseDouble(userRecePay.get("total").toString());
                //补贴金额
                Double discountConsum = Double.parseDouble(userRecePay.get("discountConsum").toString());
                //平台提成金额
                Double platformAmount = ArithUtil.mul(ArithUtil.add(total,discountConsum),Constants.SEETLE_GET);
                Map<String,Double> resultOnceMap = new HashMap<>();
                resultOnceMap.put("total",total);
                resultOnceMap.put("discountConsum",discountConsum);
                resultOnceMap.put("platformAmount",platformAmount);
                resultMap.put(businessId,resultOnceMap);
            }
        }
        List<Map<String,Object>> userReceMapByGroupBuy = bmsDxGroupBuyUseService.countUserReceGroupBuy(userReceIds);
        if(userReceMapByGroupBuy.size() > 0){
            for(Map<String,Object> userReceGroupBuy : userReceMapByGroupBuy){
                Integer businessId = Integer.parseInt(userReceGroupBuy.get("businessId").toString());
                //收入总金额
                Double total = Double.parseDouble(userReceGroupBuy.get("gac").toString());
                //补贴金额
                Double discountConsum = Double.parseDouble(userReceGroupBuy.get("dm").toString());
                //平台提成金额
                Double platformAmount = ArithUtil.mul(ArithUtil.add(total,discountConsum),Constants.SEETLE_GET);
                if(resultMap.containsKey(businessId)){
                    Map<String,Double> alreadMap = resultMap.get(businessId);
                    //收入总金额
                    Double t = alreadMap.get("total");
                    //补贴金额
                    Double dc = alreadMap.get("discountConsum");
                    //平台提成金额
                    Double plat = alreadMap.get("platformAmount");
                    t = ArithUtil.add(t,total);
                    dc = ArithUtil.add(dc,discountConsum);
                    plat = ArithUtil.add(plat,platformAmount);
                    alreadMap.put("total",t);
                    alreadMap.put("discountConsum",dc);
                    alreadMap.put("platformAmount",plat);
                    resultMap.put(businessId,alreadMap);
                }else {
                    Map<String,Double> resultOnceMap = new HashMap<>();
                    resultOnceMap.put("total",total);
                    resultOnceMap.put("discountConsum",discountConsum);
                    resultOnceMap.put("platformAmount",platformAmount);
                    resultMap.put(businessId,resultOnceMap);
                }
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> verBusinessCoupon(Integer verUserId,Integer userCouponId,Integer businessId) {
        Integer nowTime = DateTimeUtils.getNowTimeStamp();
        BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponDao.findByIdAndStatus(userCouponId,Constants.COMMON_FLAG_FALSE_INT);
        if(bmsUserReceCoupon == null){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_IS_USE,ResultMsg.CODE_BUSINESS_COUPON_IS_USE);
        }
        if(bmsUserReceCoupon.getBusinessId().intValue() != businessId.intValue()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_BELONG_BUSINESS,ResultMsg.CODE_BUSINESS_COUPON_NO_BELONG_BUSINESS);
        }
        Integer expireTime = DateTimeUtils.converDateToInterger(bmsUserReceCoupon.getExpireTime());
        if(nowTime >= expireTime){
            bmsUserReceCoupon.setStatus(Constants.IS_OVER_EXPIRE);
            bmsUserReceCouponDao.save(bmsUserReceCoupon);
            return ResultMapHelper.result(CouponEnums.COUPON_EXPIRE);
        }

        bmsUserReceCoupon.setStatus(Constants.COMMON_FLAG_TRUE_INT);
        bmsUserReceCoupon.setUseTime(new Date());
        bmsUserReceCoupon.setVerWay(BmsDxGroupBuyService.verStatusInSweep);
        bmsUserReceCoupon.setVerName(bmsUserBusinessService.findNameInStoreByUserId(verUserId,businessId));
        bmsUserReceCouponDao.save(bmsUserReceCoupon);
        List<BmsUserReceCoupon> bmsUserReceCoupons = new ArrayList<>();
        bmsUserReceCoupons.add(bmsUserReceCoupon);
        BmsCommonService.getApplicationContext().publishEvent(new UserReceEvent("receCouponVer",bmsUserReceCoupons));
        return ResultMapHelper.success(null,ResultMsg.HAND_SUCCESS);
    }

    @Override
    public Map<Integer, Integer> getUserReceOver(Integer userId, Set<Integer> businessCouponIds) {
        Map<Integer,Integer> userReceMap = new HashMap<>();
        List<Map<String,Object>> resultMap = bmsUserReceCouponDao.countUserReceCouponOver(userId,businessCouponIds);
        if(resultMap != null && resultMap.size() > 0){
            for(Map<String,Object> objectMap : resultMap){
                userReceMap.put(Integer.parseInt(objectMap.get("business_coupon_id").toString()),Constants.COMMON_FLAG_TRUE_INT);
            }
        }
        return userReceMap;
    }

    @Override
    public Map<String,Object> getMyFullCoupon_V3(ParamsMap paramsMap) {
        List<BmsUserReceCoupon> trueBmsUserReceCoupons = new LinkedList<>();
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        conditionMap.put("businessId",businessId);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_GTTE",new Date());
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getType() == Constants.BUSINESS_PRODUCE){
                    if(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType() == Constants.BUSINESS_COUPON_VOUCHERS){
                        trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                    }
                }else if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE){
                    trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                }
            }
        }
        setBmsUserReceCoupon(trueBmsUserReceCoupons);
        if(!(trueBmsUserReceCoupons != null && trueBmsUserReceCoupons.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_NO_FULL_COUPON,ResultMsg.CODE_NO_FULL_COUPON);
        }
        Map<String,Object> userDataMap = new HashMap<>();
        BmsBusiness business = null;
        BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCoupons.get(0);
        if(bmsUserReceCoupon.getType() == Constants.BUSINESS_PRODUCE){
            business = bmsUserReceCoupon.getBmsBusinessCoupon().getBmsBusiness();
        }else if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE){
            business = bmsUserReceCoupon.getBmsFullCoupon().getBmsBusiness();
        }
        userDataMap.put("bmsBusiness",business);
        return ResultMapHelper.success(trueBmsUserReceCoupons,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getMyFullCoupon_V4(ParamsMap paramsMap) {
        List<BmsUserReceCoupon> trueBmsUserReceCoupons = new LinkedList<>();
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        //conditionMap.put("businessId",businessId);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_GTTE",new Date());
        Sort sort = Sort.by(Sort.Direction.DESC,"newTime");
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),sort);
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getBusinessId() != null){
                    if(!bmsUserReceCoupon.getBusinessId().equals(businessId)){
                        continue;
                    }
                }
                if(bmsUserReceCoupon.getType() == Constants.BUSINESS_PRODUCE){
                    if(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType() == Constants.BUSINESS_COUPON_VOUCHERS){
                        trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                    }
                }else if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE){
                    trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                }
            }
        }
        setBmsUserReceCoupon(trueBmsUserReceCoupons);
        /*if(!(trueBmsUserReceCoupons != null && trueBmsUserReceCoupons.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_NO_FULL_COUPON,ResultMsg.CODE_NO_FULL_COUPON);
        }*/
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("bmsBusiness",bmsBusinessService.getBusinessById(businessId));
        return ResultMapHelper.success(trueBmsUserReceCoupons,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> showReceCouponDetail(ParamsMap paramsMap) {
        Integer receCouponId = paramsMap.getInteger("receCouponId");
        Optional<BmsUserReceCoupon> bmsUserReceCouponOptional = bmsUserReceCouponDao.findById(receCouponId);
        if(bmsUserReceCouponOptional.isPresent()){
            BmsUserReceCoupon bmsUserReceCoupon = bmsUserReceCouponOptional.get();
            List<BmsUserReceCoupon> bmsUserReceCoupons = new LinkedList<>();
            bmsUserReceCoupons.add(bmsUserReceCoupon);
            setBmsUserReceCoupon(bmsUserReceCoupons);
            if(bmsUserReceCoupon.getBmsBusinessCoupon() != null){
                bmsUserReceCoupon.getBmsBusinessCoupon().setStatus(bmsUserReceCoupon.getStatus());
            }
            return ResultMapHelper.success(bmsUserReceCoupon,ResultMsg.MSG_GET_SUCCESS);
        }
        return ResultMapHelper.success(null,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public Map<String, Object> getMyCoupons(ParamsMap paramsMap) {
        List<BmsUserReceCoupon> trueBmsUserReceCoupons = new LinkedList<>();
        Integer userId = paramsMap.getInteger("userIdentify");
        Integer businessId = paramsMap.getInteger("businessId");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId",userId);
        //conditionMap.put("businessId",businessId);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_GTTE",new Date());
        Sort sort = Sort.by(Sort.Direction.DESC,"newTime");
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),sort);
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getType() == Constants.BUSINESS_PRODUCE){
                    if(bmsUserReceCoupon.getBmsBusinessCoupon().getCouponType() == Constants.BUSINESS_COUPON_VOUCHERS){
                        trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                    }
                }else if(bmsUserReceCoupon.getType() == Constants.ACTIVITY_PRODUCE){
                    trueBmsUserReceCoupons.add(bmsUserReceCoupon);
                }
            }
        }
        setBmsUserReceCoupon(trueBmsUserReceCoupons);
        if(!(trueBmsUserReceCoupons != null && trueBmsUserReceCoupons.size() > 0)){
            return ResultMapHelper.result(ResultCode.CODE_NO_FULL_COUPON,ResultMsg.CODE_NO_FULL_COUPON);
        }
        Map<String,Object> userDataMap = new HashMap<>();
        userDataMap.put("bmsBusiness",bmsBusinessService.getBusinessById(businessId));

        return ResultMapHelper.success(trueBmsUserReceCoupons,userDataMap,ResultMsg.MSG_GET_SUCCESS);
    }

    @Override
    public boolean checkCouponBelongBusiness(Integer businessId, Integer receId) {
        Optional<BmsUserReceCoupon> bmsUserReceCoupon = bmsUserReceCouponDao.findById(receId);
        if(bmsUserReceCoupon.isPresent()){
            return businessId.equals(bmsUserReceCoupon.get().getBusinessId());
        }
        return false;
    }
}
